package cn.loioi.distribution.db;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

public class DbConnoction {
	private final Connection connection;

	private boolean rollbackOnly = false;
	private List<Statement> statements = null;
	private List<ResultSet> resultSets = null;

	public DbConnoction(DataSource dataSource) throws SQLException {
		this.connection = dataSource.getConnection();
	}

	/**
	 * 获取当前连接
	 * @return
	 */
	public Connection getConnection() {
		return connection;
	}

	/**
	 * 创建查询声明
	 * @return
	 * @throws SQLException
	 */
	public Statement createStatement() throws SQLException {
		return addStatement(connection.createStatement());
	}

	/**
	 * 创建查询声明
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	public PreparedStatement prepareStatement(String sql) throws SQLException {
		return addStatement(connection.prepareStatement(sql));
	}

	/**
	 * 创建 call 方式 的查询声明
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	public CallableStatement prepareCall(String sql) throws SQLException {
		return addStatement(connection.prepareCall(sql));
	}

	/**
	 * 添加被管理的查询声明
	 * @param stm
	 * @return
	 */
	private <S extends Statement> S addStatement(S stm) {
		if (statements == null) statements = new ArrayList<>();

		statements.add(stm);

		return stm;
	}

	/**
	 * 添加被管理查询返回集
	 * @param result
	 * @return
	 */
	public <R extends ResultSet> R addResultSet(R result) {
		if (resultSets == null) resultSets = new ArrayList<>();

		resultSets.add(result);

		return result;
	}

	/**
	 * 判断是不是回滚
	 * @return
	 */
	public boolean isRollbackOnly() {
		return rollbackOnly;
	}

	/**
	 * 设置为回滚
	 */
	public void setRollbackOnly() {
		this.rollbackOnly = true;
	}

	/**
	 * 设置是否自动提交
	 * @param autoCommit
	 * @throws SQLException
	 */
	public void setAutoCommit(boolean autoCommit) throws SQLException {
		getConnection().setAutoCommit(autoCommit);
	}

	/**
	 * 事务提交
	 * @throws SQLException
	 */
	public void commit() throws SQLException {
		getConnection().commit();
	}

	/**
	 * 事务回滚
	 * @throws SQLException
	 */
	public void rollback() throws SQLException {
		getConnection().rollback();
	}

	/**
	 * 关闭连接
	 * @throws SQLException
	 */
	public void close() throws SQLException {
		// 关闭返回集
		if (resultSets != null) {
			for (ResultSet result : resultSets) {
				result.close();
			}
		}
		// 关闭查询声明
		if (statements != null) {
			for (Statement stm : statements) {
				stm.close();
			}
		}
		// 关闭连接
		connection.close();
	}
}
